import random
import string
from datetime import datetime, timedelta
from flask import render_template, redirect, url_for, flash, request
from flask_login import login_user, logout_user, login_required, current_user
from extensions import db, mail
from flask_mail import Message
from . import auth_bp_zc
from .models import User_zc, Captcha_zc
from .forms import LoginForm, RegisterForm, VerifyEmailForm

def generate_captcha():
    """生成6位数字验证码"""
    return ''.join(random.choices(string.digits, k=6))

@auth_bp_zc.route('/login', methods=['GET', 'POST'])
def login():
    """用户登录"""
    if current_user.is_authenticated:
        return redirect(url_for('main_bp_zc.index'))
    
    form = LoginForm()
    if form.validate_on_submit():
        user = User_zc.query.filter_by(username=form.username.data).first()
        if user and user.check_password(form.password.data):
            login_user(user, remember=form.remember.data)
            next_page = request.args.get('next')
            return redirect(next_page or url_for('main_bp_zc.index'))
        flash('用户名或密码错误', 'danger')
    return render_template('auth/login.html', form=form)

@auth_bp_zc.route('/register', methods=['GET', 'POST'])
def register():
    """用户注册"""
    if current_user.is_authenticated:
        return redirect(url_for('main_bp_zc.index'))
    
    form = RegisterForm()
    if form.validate_on_submit():
        # 验证验证码
        captcha = Captcha_zc.query.filter_by(
            email=form.email.data,
            code=form.captcha.data,
            is_used=False
        ).first()
        
        if not captcha or (datetime.utcnow() - captcha.created_at) > timedelta(minutes=10):
            flash('验证码无效或已过期', 'danger')
            return redirect(url_for('auth_bp_zc.register'))
        
        user = User_zc(
            username=form.username.data,
            email=form.email.data,
            nickname=form.nickname.data,
            is_active=True  # 直接激活用户
        )
        user.set_password(form.password.data)
        
        # 标记验证码为已使用
        captcha.is_used = True
        
        db.session.add(user)
        db.session.commit()
        
        flash('注册成功，请登录', 'success')
        return redirect(url_for('auth_bp_zc.login'))
    return render_template('auth/register.html', form=form)

@auth_bp_zc.route('/send_captcha', methods=['POST'])
def send_captcha():
    """发送验证码"""
    email = request.form.get('email')
    if not email:
        return {'status': 'error', 'message': '邮箱不能为空'}, 400
    
    # 生成验证码
    captcha = generate_captcha()
    
    # 保存验证码
    captcha_record = Captcha_zc(email=email, code=captcha)
    db.session.add(captcha_record)
    db.session.commit()
    
    # 发送邮件
    msg = Message(
        '邮箱验证 - 张驰的个人空间',
        recipients=[email]
    )
    msg.html = render_template(
        'email/verify_email_zc.html',
        captcha=captcha
    )
    mail.send(msg)
    
    return {'status': 'success', 'message': '验证码已发送'}

@auth_bp_zc.route('/verify_email', methods=['GET', 'POST'])
def verify_email():
    """邮箱验证"""
    form = VerifyEmailForm()
    if form.validate_on_submit():
        user = User_zc.query.filter_by(email=form.email.data).first()
        if not user:
            flash('用户不存在', 'danger')
            return redirect(url_for('auth_bp_zc.verify_email'))
        
        captcha = Captcha_zc.query.filter_by(
            email=form.email.data,
            code=form.captcha.data,
            is_used=False
        ).first()
        
        if not captcha or (datetime.utcnow() - captcha.created_at) > timedelta(minutes=10):
            flash('验证码无效或已过期', 'danger')
            return redirect(url_for('auth_bp_zc.verify_email'))
        
        user.is_active = True
        captcha.is_used = True
        db.session.commit()
        
        flash('邮箱验证成功，请登录', 'success')
        return redirect(url_for('auth_bp_zc.login'))
    return render_template('auth/verify_email.html', form=form)

@auth_bp_zc.route('/logout')
@login_required
def logout():
    """用户登出"""
    logout_user()
    flash('已退出登录', 'info')
    return redirect(url_for('main_bp_zc.index')) 